<?php

namespace Common\Controller;
use Common\Controller;

class DfcommonController extends AdminbaseController{
	// const MODEL = 'XXMoudel'; 当前维护数据表模型
	/**
	 * 查询条件字段
	 * @var array
	 */
	protected $list_search_field = array();
	/**
	 * 列表默认显示内容字段
	 * @var array
	*/
	protected $list_show_field = array();
	/**
	 * 列表默认不显示内容字段
	 * @var array
	 */
	protected $list_disable_field = array('password', 'user_pass');
	/**
	 * 不能添加修改 字段
	 * @var array
	 */
	protected $list_disable_edit_field = array('id', 'ctime', 'cdate', 'udate', 'utime');
	
	/**
	 * 列表默认显示功能按钮
	 * @var array
	 */
	protected $list_show_but = array(
		'check' => '审核',
		'top' => '置顶',
		'recommend' => '推荐',
		'comment' => '评论'
	);
	
	public $action = array();	
	protected $default_action = array(
		"index" => "index",
		"recyclebin" => "recyclebin",
		"add" => "add",
		"doadd" => "doadd",
		"edit" => "edit",
		"doedit" => "doedit",
		"del" => "dodel",
		"undel" => "doundel",
		"upload" => "upload",
		
		'listorders' => 'listorders',
		'check' => 'check',
		'top' => 'top',
		'recommend' => 'recommend',
		'comment' => 'comment',
		'delete' => 'delete',
	);
	public $template = array();
	protected $default_template = array(
		"index" => 'Common/index',
		"add" => 'Common/add',
		"edit" => 'Common/edit',
		"recyclebin" => "Common/recyclebin",
	);
	public function __construct() {
		parent::__construct();
		$this->action = array_merge($this->default_action, (array)$this->action);
		$className = str_replace("Controller", '', substr(get_class($this), strrpos(get_class($this), "\\" )+ 1));
		foreach ($this->action as $k => $v ) {
			$this->action[$k] = $className . "/" . $v;
		}
		
		$this->template = array_merge($this->default_template, (array)$this->template);
	}
	// ==================  权限控制方法 ====== start ===============
	/**
	 * 获取列表显示字段
	 * @param string $role 当前用户角色
	 * @return array $langs
	 */
	protected function _get_field_show($role='当前用户角色'){
		// 查询所有字段
		$langs = D(static::MODEL)->_getLang();
		// 获取只显示的字段
		if ( !empty($this->list_show_field)) {
			$langs = array_intersect_key($langs, array_flip($this->list_show_field));
		}
		// 去除不显示的字段
		if ( !empty($this->list_disable_field)) {
			$langs = array_diff_key($langs, array_flip($this->list_disable_field));
		}
		return $langs;
	}
	/**
	 * 获取添加 修改 显示字段
	 * @param string $role 当前用户角色
	 * @return array $langs
	 */
	protected function _get_field_edit($role='当前用户角色'){
		$langs = D(static::MODEL)->_getLang();
		$langs = array_diff_key($langs, array_flip($this->list_disable_edit_field));
		$pk = D(static::MODEL)->_getPk();
		unset($langs[$pk]);
		return $langs;
	}
	/**
	 * 获取列表页面查询字段
	 * @param string $role 当前用户角色
	 * @return array $langs
	 */
	protected function _get_field_search($role='当前用户角色'){
		$langs = D(static::MODEL)->_getLang();
		$langs = array_intersect_key($langs, array_flip($this->list_search_field));
		return $langs;
	}
	/**
	 * 获取列表页面功能按钮
	 * @param string $role 当前用户角色
	 * @return array $langs
	 */
	protected function _get_but_action($role='当前用户角色'){
		return $this->list_show_but;
	}
	// ==================  权限控制方法 ====== start ===============

	
	
	// ===================== 基本数据管理 开始 === start==================
	/**
	 * 列表
	 */
	public function index(){
		$this->_list(1);
		$this->display($this->template[__FUNCTION__]);
	}
	
	// 回收站
	public function recyclebin(){
		$this->_list(-1);
		$this->display($this->template[__FUNCTION__]);
	}
	
	protected function _list($act) {
		// 查询显示字段
		
		$langs = $this->_get_field_show();
		$where_list_fileds = $this->_get_field_search();
		
		$where = I('where'); // 查询条件
		$where = array_intersect_key($where, $where_list_fileds);
		$where = array_filter($where); // 过滤空值的key
		$where['status'] = $act === 1 ? 1 : -1; // 回收站状态 1 可用 -1 删除
		
		$model = D(static::MODEL);
		$count = $model->_count($where); // 获取数据总数
		$page = $this->page($count, 20); // 获取分页
		
		$data = array();
		// 获取数据列表
		$count && $data = (array)$model->_getList($where, $page->firstRow . ',' . $page->listRows);
		
		$langs['pool']["lang"] = '管理';
		
		$pk = $model->_getPk();
		
		// 拼装数据
		foreach ($data as &$item) {
			$pool = array();
			if (isset($where['status']) && $where['status'] == -1) {
				// 回收站 默认显示的操作项目
				$link = U($this->action['undel'], array($pk=>$item[$pk]));
				$pool[] = '<a class="js-ajax-delete" href="'.$link.'" >恢复</a>';
			} else {
				// 前台列表 默认显示的操作项目
				$link = U($this->action['edit'],array($pk=>$item[$pk]));
				$pool[] = '<a href="'.$link.'" >编辑</a>';
				$link = U($this->action['del'],array($pk=>$item[$pk]));
				$pool[] = '<a class="js-ajax-delete" href="'.$link.'" >删除</a>';
			}
			$item['pool'] = implode(" | ", $pool);
		}
		// 分页输出
		
		$this->assign("count", $count);
		$this->assign("Page", $page->show('Admin'));
		$this->assign("current_page",$page->GetCurrentPage());
		// 主键名称
		$this->assign('pk', $pk);
		// 查询条件
		$this->assign('where', $where);
		// 显示字段
		$this->assign('lang', $langs);
		// 列表数据
		$this->assign('volist', $data);
		// 跳转链接地址
		$this->assign('action', $this->action);
		// 功能按钮
		$buttonlist = $this->_get_but_action();
		$this->assign('buttonlist', $buttonlist);
		//  查询字段输出
		$this->assign('where_list', $where_list_fileds);
		
		unset($_GET[C('VAR_URL_PARAMS')]);
	}
	
	/**
	 * 添加
	 */
	public function add(){
		$langs = $this->_get_field_edit();
		$pk = D(static::MODEL)->_getPk();
		unset($langs[$pk]);
		foreach ($langs as $key => $item) {
			!isset($item['show_pos']) && $item['show_pos'] = 'left';
			$show_langs[$item['show_pos']][$key] = $item;
		}
		$this->assign('lang', $show_langs);
		$this->assign('action', $this->action);
		$this->display($this->template[__FUNCTION__]);
	}

	/**
     * 执行添加方法
     */
    public function doadd(){
    	$model = D(static::MODEL);
    	$langs = $this->_get_field_edit();
    	$pk = $model->_getPk();
    	unset($langs[$pk]);
    	$post = I();
    	$data = $this->_getPostDataByAddEdit($langs, $post);
    	
    	$res = $model->_add($data);
    	if ($res) {
    		$this->success('数据添加成功', U($this->action['index']));
    	} else {
    		$this->error('数据添加失败', $this->action['add']);
    	}
    }

	/**
	 * 修改
	 */
	public function edit(){
		$model = D(static::MODEL);
		$pk = $model->_getPk();
		$id = intval(I($pk, 0));
		if ($id == 0) {
			$this->error('请求参数错误，请从正规流程进入！！', U($this->action['index']));
		}
		
		$langs = $this->_get_field_edit();
		foreach ($langs as $key => $item) {
			!isset($item['show_pos']) && $item['show_pos'] = 'left';
			$show_langs[$item['show_pos']][$key] = $item;
		}
		$item = $model->_getInfo($id);
		$this->assign('pk', $pk);
		$this->assign('lang', $show_langs);
		$this->assign('action', $this->action);
		$this->assign('item', $item);
		$this->display($this->template[__FUNCTION__]);
	}

	/**
     * 执行修改方法
     */
    public function doedit(){
    	$model = D(static::MODEL);
    	$pk = $model->_getPk();
    	$langs = $this->_get_field_edit();
    	$post = I();
    	$data = $this->_getPostDataByAddEdit($langs, $post);
    	$data[$pk] = I("post.".$pk);
    	$res = $model->_save($data);
    	if ($res) {
    		$this->success('数据修改成功', U($this->action['index']));
    	} else {
    		$url = U($this->action['edit'], array($pk, $data['id']));
    		$this->error('数据修改失败', $url);
    	}
    }
	/**
	 * 执行删除方法
	 */
	public function dodel() {
	    $model = D(static::MODEL);
	    $pk = $model->_getPk();
	    $data['status'] = -1;
	    $data[$pk] = I($pk);
	    if (empty($data[$pk])) {
    	    $data[$pk] = I("post.".$pk);
	    }
	    if (empty($data[$pk])) {
	        $this->success('请从正确途径删除数据', U($this->action['index']));
	    }
	    $res = $model->_save($data);
	    if ($res) {
	        $this->success('数据删除成功', U($this->action['index']));
	    } else {
	        $url = U($this->action['edit'], array($pk, $data['id']));
	        $this->error('数据删除失败', $url);
	    }
	}
	public function doundel() {
	    $model = D(static::MODEL);
	    $pk = $model->_getPk();
	    $data['status'] = 1;
	    $data[$pk] = I($pk);
	    if (empty($data[$pk])) {
    	    $data[$pk] = I("post.".$pk);
	    }
	    if (empty($data[$pk])) {
	        $this->success('请从正确途径操作数据', U($this->action['index']));
	    }
	    $res = $model->_save($data);
	    if ($res) {
	        $this->success('数据恢复成功', U($this->action['recyclebin']));
	    } else {
	    	$this->success('数据恢复失败', U($this->action['recyclebin']));
	    }
	}
	
	//排序
	public function listorders() {
		$model = D(static::MODEL);
		$pk = $model->getPk(); //获取主键名称
		$ids = $_POST['listorders'];
		foreach ($ids as $key => $r) {
			$data['listorder'] = $r;
			$model->where(array($pk => $key))->save($data);
		}
		$this->success("排序更新成功！");
	}
	// 删除
	function delete(){
		$data['status'] = -1;
		$model = D(static::MODEL);
		$update_status = 'status'; // 需要更新的状态字段
		$where = $this->_act_before();
	
		$data[$update_status] = -1;
		if ($model->where($where)->save($data) !== false) {
			$this->success("删除成功！");
		} else {
			$this->error("删除失败！");
		}
	}
	
	// 简单操作前置 方法 审核 置顶 推荐 
	final public function _act_before() {
		$model = D(static::MODEL);
		$pk = $model->getPk(); //获取主键名称
		if(!isset($_POST[$pk])) {
			return false;
		}
		
		$ids = I('post.'.$pk);
		array_filter($ids, 'is_numeric');
		$where = $pk . " in (" . implode(",", $ids) . ")";
		return $where;
	}
	
	
	/**
	 * 魔术方法 有不存在的操作的时候执行
	 * @access public
	 * @param string $method 方法名
	 * @param array $args 参数
	 * @return mixed
	 */
	public function __call($method,$args) {
		$this->list_show_but = array(
			'check' => '审核',
			'top' => '置顶',
			'recommend' => '推荐',
			'comment' => '评论'
		);
		
		if (isset($this->list_show_but[$method])) {
			$model = D(static::MODEL);
			$update_status = $method; // 需要更新的状态字段
			$where = $this->_act_before();
			
			if ($_GET[$method]) {
				$data[$update_status] = 1;
				if ($model->where($where)->save($data) !== false) {
					$this->success($this->list_show_but[$method] . "成功！");
				} else {
					$this->error($this->list_show_but[$method] . "失败！");
				}
			}
			
			if ($_GET["un".$method]) {
				$data[$update_status] = 2;
				if ($model->where($where)->save($data)) {
					$this->success("取消".$this->list_show_but[$method]."成功！");
				} else {
					$this->error("取消".$this->list_show_but[$method]."失败！");
				}
			}
			return true;
		}
		
		$this->error('该页面不存在！');
	}
	
	
	
	// 彻底删除
	function clean(){
		$model = D(static::MODEL);
		$where = $this->_act_before();
		
		if ($model->where($where)->delete() !== false) {
			$this->success("彻底删除成功！");
		} else {
			$this->error("彻底删除失败！");
		}
	}
	/**
	 * 获取 添加修改数据
	 * @param array $langs 模型字段映射表
	 * @param array $post  post表单数据
	 * @return array 需要添加到数据库的数据
	 */
	protected function _getPostDataByAddEdit($langs, $post) {
		$data = array();
		foreach ($langs as $k => $lang) {
			switch ($lang['show_type']) {
				case 'json':
					$tmp = array();
					foreach ($post[$k] as $v) {
						if (!empty($v[1])) {
							$tmp[$v[0]] = $v[1];
						}
					}
					$tmp = array_unique($tmp);
					$data[$k] = json_encode($tmp);
					break;
				case 'text' :
				case 'textedit' :
					$data[$k] = htmlspecialchars_decode($post[$k]);
					break;
				case 'multiFile' :
					$url_list = array();
					if(!empty($post[$k . '_filename']) && !empty($post[$k.'_fileurl'])) {
						$url_filename = $post[$k . '_filename'];
						foreach ($post[$k.'_fileurl'] as $key=>$url){
							$photourl = sp_asset_relative_url($url);
							$url_list[] = array("url" => $photourl, "alt"=>$url_filename[$key]);
						}
					}
					$data[$k] = json_encode($url_list, JSON_UNESCAPED_UNICODE );
					break;
				case 'multiImage' :
					$url_list = array();
					if(!empty($post[$k . '_alt']) && !empty($post[$k.'_url'])) {
						$url_alt = $post[$k . '_alt'];
						foreach ($post[$k.'_url'] as $key=>$url){
							$photourl = sp_asset_relative_url($url);
							$url_list[] = array("url" => $photourl, "alt"=>$url_alt[$key]);
						}
					}
					$data[$k] = json_encode($url_list, JSON_UNESCAPED_UNICODE );
					break;
				case 'image' :
					$data[$k] = sp_asset_relative_url($post[$k]);
					break;
				case 'datetime' :
					$data[$k] = strtotime($post[$k]);
					break;
				default:
					$data[$k] = $post[$k];
					break;
			}
		}
		return $data;
	}
	// ===================== 基本数据管理  ===结束 end ===================
}